#!/usr/bin/env python

"""
Name: 'GVFX Gui'
"""				
__author__ = "Emanuel Timbis Lopez"  
__url__ = ("http://timbis.com.ar")
__version__ = "0.1"

import sys
try:
	import pygtk
  	pygtk.require("2.0")
except:
  	pass
try:
	import gtk
  	import gtk.glade
except:
	print >> sys.stderr, "You need to install the python gtk bindings"
	sys.exit(1)

try:
    	import vte
except:
    	error = gtk.MessageDialog (None, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
        'You need to install python bindings for libvte')
   	error.run()
    	sys.exit (1)

import gobject
import gnome.ui
import commands 
import os.path
import subprocess
from subprocess import Popen, PIPE
import string
import thread, time
import Image


class GVFX:

    def __init__(self):

	#Main
	self.glade = gtk.glade.XML("gvfx.glade");                    
        self.glade.signal_autoconnect(self)                                  
	
	#Evitamos variables vacias
	self.archivo_name = ""
	self.archivo_name2 = ""
	self.frameinic = "1"
	self.framefin = "2"
	self.frameinic2 = "1"
	self.framefin2 = "2"
	self.fps = "25"

	#Conectamos Widgets
	self.glade.signal_connect("on_frameinic_value_changed", self.on_spin_change)
	self.spin = self.glade.get_widget("frameinic")
	self.glade.signal_connect("on_framefin_value_changed", self.on_spin_change2)
	self.spin2 = self.glade.get_widget("framefin")
	self.glade.signal_connect("on_frameinic2_value_changed", self.on_spin_change3)
	self.spin3 = self.glade.get_widget("frameinic2")
	self.glade.signal_connect("on_framefin2_value_changed", self.on_spin_change4)
	self.spin4 = self.glade.get_widget("framefin2")
	self.glade.signal_connect("on_fps_value_changed", self.on_spin_change5)
	self.spin5 = self.glade.get_widget("fps")
	self.combo = self.glade.get_widget("format")
	self.combo.set_active(0)
	self.combo2 = self.glade.get_widget("size")
	self.combo2.set_active(0)

	#Timeline video 1
	w = self.glade.get_widget("GVFX")
	self.area = self.glade.get_widget("area")
	self.area.drag_dest_set(0, [], 0)
	#Conectamos area de "Arrastrar y soltar"
	self.area.connect('drag_motion', self.motion_cb)
	self.area.connect('drag_drop', self.drop_cb)
        self.area.connect('drag_data_received', self.got_data_cb)
	self.area.connect("expose_event", self.on_expose)


	#Timeline video 2
	self.area2 = self.glade.get_widget("area2")
	self.area2.drag_dest_set(0, [], 0)
	#Conectamos area de "Arrastrar y soltar"
	self.area2.connect('drag_motion', self.motion_cb2)
	self.area2.connect('drag_drop', self.drop_cb2)
	self.area2.connect('drag_data_received', self.got_data_cb2)
	self.area2.connect("expose_event", self.on_expose2)

	#Barra de estado
	self.salida = self.glade.get_widget("salida")
	gobject.timeout_add(2000, self.actualizacion)

	

	w.show_all()
	gtk.main()  

#--------------------Muestra miniaturas en areas drag and drop--------#
	
    def on_expose(self, widget, event):
	#Carga la miniatura generada - video 1
	widget = self.area
        self._img = gtk.gdk.pixbuf_new_from_file("a.jpg")
	cr = widget.window.cairo_create()
        cr.set_source_pixbuf(self._img, 0, 0)
        cr.paint()

    def on_expose2(self, widget, event):
	#Carga la miniatura generada - video 2
	widget = self.area2
        self._img2 = gtk.gdk.pixbuf_new_from_file("b.jpg")
	cr2 = widget.window.cairo_create()
        cr2.set_source_pixbuf(self._img2, 0, 0)
        cr2.paint()

#--------------------Barra de estado-----------------------------------#
    def actualizacion(self):
	self.salida.set_label("Listo")
	gobject.timeout_add(2000, self.actualizacion)

#---------------------Configuracion frames transiciones----------------#
    def on_spin_change (self, w):
	self.frameinic = self.spin.get_value_as_int();

    def on_spin_change2 (self, w):
	self.framefin = self.spin2.get_value_as_int();

    def on_spin_change3 (self, w):
	self.frameinic2 = self.spin3.get_value_as_int();

    def on_spin_change4 (self, w):
	self.framefin2 = self.spin4.get_value_as_int();

    def on_spin_change5 (self, w):
	self.fps = self.spin5.get_value_as_int();

#---------------------Configuracion video final-----------------------#

    #Evento formato
    def on_format_changed (self,w):
	model = self.combo.get_model()
   	activo = self.combo.get_active()
    	self.format = model[activo][0]

    #Evento resolucion
    def on_size_changed (self,w):
	model2 = self.combo2.get_model()
   	activo2 = self.combo2.get_active()
    	self.size = model2[activo2][0]

    #Evento renderizacion 
    def on_Go_clicked(self, widget):
	print("Renderizando...") 
        l_command = commands.getstatusoutput("blender -b gfvx.blend -P gfvx_script.py")
	self.salida.set_label("Renderizando")
	l2_command = commands.getstatusoutput("notify-send Renderizacion Competada")

    #Evento guardar
    def on_guardar_clicked(self, widget):
	file = open("data1.txt", "w")
	file.write(self.archivo_name)
	file.write(",")
	file.write(str(self.frameinic))
	file.write(",")
	file.write(str(self.framefin))
	file.write(", \n")
	file.write(self.archivo_name2)
	file.write(",")
	file.write(str(self.frameinic2))
	file.write(",")
	file.write(str(self.framefin2))
	file.write(", \n")
	file.write(str(self.fps))
	file.write(",")
	file.write(str(self.size))
	file.write(",")
	file.write(str(self.format))
	file.write(", \n")
	file.write(str(self.scene))
	file.write(",")
	file.close()
	self.salida.set_label("Configuracion guardada, presione Renderizar")
	


#--------------------Botones de transiciones--------------------------------#
    def on_11_clicked (self,w):
	self.scene = "01.00001"
	self.salida.set_label("Transicion seleccionada")
    def on_12_clicked (self,w):
	self.scene = "01.00002"
	self.salida.set_label("Transicion seleccionada")
    def on_13_clicked (self,w):
	self.scene = "01.00003"
	self.salida.set_label("Transicion seleccionada")
    def on_14_clicked (self,w):
	self.scene = "01.00004"
	self.salida.set_label("Transicion seleccionada")
    def on_15_clicked (self,w):
	self.scene = "01.00005"
	self.salida.set_label("Transicion seleccionada")

    def on_22_clicked (self,w):
	self.scene = "02.00002"
	self.salida.set_label("Transicion seleccionada")
    def on_23_clicked (self,w):
	self.scene = "02.00003"
	self.salida.set_label("Transicion seleccionada")
    def on_24_clicked (self,w):
	self.scene = "02.00004"
	self.salida.set_label("Transicion seleccionada")
    def on_25_clicked (self,w):
	self.scene = "02.00005"
	self.salida.set_label("Transicion seleccionada")
    def on_26_clicked (self,w):
	self.scene = "02.00006"
	self.salida.set_label("Transicion seleccionada")
    def on_27_clicked (self,w):
	self.scene = "02.00007"
	self.salida.set_label("Transicion seleccionada")
    def on_28_clicked (self,w):
	self.scene = "02.00007"
	self.salida.set_label("Transicion seleccionada")

    def on_31_clicked (self,w):
	self.scene = "03.00001"
	self.salida.set_label("Transicion seleccionada")
    def on_32_clicked (self,w):
	self.scene = "03.00002"
	self.salida.set_label("Transicion seleccionada")

    def on_42_clicked (self,w):
	self.scene = "04.00002"
	self.salida.set_label("Transicion seleccionada")
    def on_43_clicked (self,w):
	self.scene = "04.00003"
	self.salida.set_label("Transicion seleccionada")

    def on_51_clicked (self,w):
	self.scene = "05.00001"
	self.salida.set_label("Transicion seleccionada")
    def on_52_clicked (self,w):
	self.scene = "05.00002"
	self.salida.set_label("Transicion seleccionada")
    def on_53_clicked (self,w):
	self.scene = "05.00003"
	self.salida.set_label("Transicion seleccionada")
    def on_54_clicked (self,w):
	self.scene = "05.00004"
	self.salida.set_label("Transicion seleccionada")
    def on_55_clicked (self,w):
	self.scene = "05.00005"
	self.salida.set_label("Transicion seleccionada")
    def on_56_clicked (self,w):
	self.scene = "05.00006"
	self.salida.set_label("Transicion seleccionada")

    def on_61_clicked (self,w):
	self.scene = "06.00001"
	self.salida.set_label("Transicion seleccionada")
    def on_62_clicked (self,w):
	self.scene = "06.00002"
	self.salida.set_label("Transicion seleccionada")

#---------------------Arrastrar y soltar video 1 y 2 -----------------------#

    #Video 1
    def motion_cb(self,wid, context, x, y, time):
	#Sensor si hay informacion arrastrandose sobre el Area de Dibujo   	
  	context.drag_status(gtk.gdk.ACTION_COPY, time)
	print("Motion")
	return True
    def drop_cb(self,wid, context, x, y, time):
  	# La informacion arrastrada se suelta
   	wid.drag_get_data(context, context.targets[-1], time)
	print("Recibido")
	return True


    def got_data_cb(self,wid, context, x, y, data, info, time):
    	# Cuando se suelte la informacion esto lo imprime en pantalla.
	archivo_namepre = data.get_text()
	longitud = len(archivo_namepre)
	self.archivo_name = archivo_namepre[7:longitud-1]
	context.finish(True, False, time)
	
	#Crea miniatura
	os.system('rm -f a.jpg')
       	os.system('mplayer -nosound -vo jpeg -frames 1 -ss 00:00:01 %s -loop 1' % self.archivo_name)
	im1 = Image.open("00000001.jpg")
	im2 = im1.resize((100, 100), Image.ANTIALIAS)
	im2.save("a.jpg")
		
	#Calcula los frames para el inicio de la transicion
	try:
       		fps =     os.popen('mplayer -vo null -ao null -frames 0 -identify %s | grep ID_VIDEO_FPS | cut -d "=" -f2 | cut -d "." -f1' % self.archivo_name) 
       		sec =     os.popen('mplayer -vo null -ao null -frames 0 -identify %s | grep ID_LENGTH | cut -d "=" -f2 | cut -d "." -f1' % self.archivo_name)
       		vinfo = int(fps.read())
       		tiempo = int(sec.read())
		framesfinales = vinfo*tiempo
		self.framefin = framesfinales
		self.frameinic = framesfinales - 50

	except IOError:
       		print "No se pudo obtener informacion del video"

       
	self.on_expose(1,2) #Ejecuta la funcion para el cambio de miniatura


    #Video 2
    def motion_cb2(self,wid, context, x, y, time):
	#Sensor si hay informacion arrastrandose sobre el Area de Dibujo   	
  	context.drag_status(gtk.gdk.ACTION_COPY, time)
	print("Motion")
	return True
    def drop_cb2(self,wid, context, x, y, time):
  	# La informacion arrastrada se suelta
   	wid.drag_get_data(context, context.targets[-1], time)
	print("Recibido")
    	return True
    def got_data_cb2(self,wid, context, x, y, data, info, time):
    	# Cuando se suelte la informacion esto lo imprime en pantalla.
	archivo_namepre = data.get_text()
	longitud = len(archivo_namepre)
	self.archivo_name2 = archivo_namepre[7:longitud-1]
    	context.finish(True, False, time)
	#Calcula los frames para la finalizacion de la transicion
	self.framefin2 = 50
	self.frameinic2 = 1
	
	#Crea miniatura
	os.system('rm -f b.jpg')
       	os.system('mplayer -nosound -vo jpeg -frames 1 -ss 00:00:01 %s -loop 1' % self.archivo_name2)
	im1 = Image.open("00000001.jpg")
	im2 = im1.resize((100, 100), Image.ANTIALIAS)
	im2.save("b.jpg")
	self.on_expose2(1,2) #Ejecuta la funcion para el cambio de miniatura
	

    def gtk_main_quit(self, widget, data=None):
	os.system('rm -f a.jpg')
	os.system('rm -f b.jpg')
	os.system('rm -f 00000001.jpg')
        gtk.main_quit()
        return False

if __name__ == "__main__":
    app = GVFX()
    


